<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <p>接受的消息：<span></span></p>
      <section style="display: none">
        <input type="text" placeholder="随便写点什么" />
        <button>确认</button>
      </section>
    </div>
    <script>
      let initialized = false,
        targetWindow,
        targetOrigin
      const inputEle = document.querySelector('input')
      const msgEle = document.querySelector('span')

      const init = ({ data, origin, source }) => {
        document.querySelector('section').style.display = 'block'
        targetWindow = source.window
        targetOrigin = origin
      }

      document.querySelector('button').addEventListener('click', () => {
        targetWindow.postMessage(inputEle.value, targetOrigin)
      })

      window.addEventListener('message', (event) => {
        msgEle.innerHTML = event.data
        if (!initialized) init(event)
      })
    </script>
  </body>
</html>
